import { createRouter, createWebHistory } from 'vue-router';
import Layout from '../views/Layout/index.vue'; // 首页
import Home from '../views/Home/Home.vue'; // 主页
import Login from '../views/Login/Login.vue'; // 登录
import NotFound from '@/views/NotFound/index.vue'; // 引入 404页面
import UserInfo from '@/views/backstage/UserInfo.vue'; // 用户管理
import Post from '@/views/backstage/Post.vue'; // 岗位管理
import LogManagement from '@/views/system/LogManagement.vue'; // 日志管理
import NoticeAnnouncement from '@/views/system/noticeAnnouncement.vue'; // 通知公告

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '',
      component: Layout,
      children: [ 
        {
          path: '/NotFound', // 404页面
          name: 'NotFound',
          component: NotFound,
        },
        {
          path: '',
          name: 'home',
          component: Home,
        },
        {
          path: '/user', // 用户管理
          name: 'user',
          component: UserInfo,
        },
        {
          path: '/post', // 岗位管理
          name: 'post',
          component: Post,
        },
        {
          path: '/noticeAnnouncement', // 通知公告
          name: 'noticeAnnouncement',
          component: NoticeAnnouncement,
        },
        {
          path: '/logManagement', // 日志管理
          name: 'logManagement',
          component: LogManagement,
        },
        // 其他路由规则...
        {
          path: '/:pathMatch(.*)*', // 通配符路由，匹配所有未匹配的路径
          name: 'NotFound',
          component: NotFound,
        },
      ],
    },
    {
      path: '/login', // 登录
      name: 'login',
      component: Login,
    },
  ],
});

router.beforeEach((to, from, next) => {
  // 在这里写你的逻辑，例如检查用户是否已登录
  const isAuthenticated = localStorage.getItem('token');
  if (to.name !== 'login' && !isAuthenticated) {
    // 如果用户尝试进入非登录页面且未登录，重定向到登录页面
    next({ name: 'login' });
  } else {
    // 否则正常继续路由跳转
    next();
  }
});

export default router;
